<template>
  <Dialog v-model="dialogVisible" title="标题">
    <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="formRules">
      <el-form-item label=" " prop="inputTitle">
        <el-input
          v-model="formData.inputTitle"
          placeholder="请输入项目标题"
          maxlength="30"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
const dialogVisible = ref(false)
const formLoading = ref(false) // 表单的加载中:1）修改时的数据加载；2）提交的按钮禁用
const message = useMessage() // 消息弹窗
const formData = ref({} as any)
const formRules = reactive({
  inputTitle: [{ required: true, message: '项目标题不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (title) => {
  dialogVisible.value = true
  resetForm()
  formData.value.inputTitle = title
}
const resetForm = () => {
  formData.value = {
    inputTitle: ''
  }
  formRef.value?.resetFields()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
const emit = defineEmits(['success'])

/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  dialogVisible.value = false
  // 发送操作成功的事件
  emit('success', formData.value.inputTitle)
}
</script>

<style scoped></style>
